package utils;

import book.PairOfUidAndBookId;
import com.bit.utils.FileUtils;

import java.io.IOException;

public class AnalyzingBorrowedBook {
    public PairOfUidAndBookId[] loadBorrowedBook(String filename)throws IOException{
        String content = FileUtils.readFile(filename);
        if(content == null || content.isEmpty()){
            System.out.println("已借阅书籍列表无数据, 表示没有用户借阅过书籍");
            return null;
        }

        String[] jsonStrings = content.split("\n");
        PairOfUidAndBookId[] pairOfUidAndBookIds = new PairOfUidAndBookId[jsonStrings.length];

        for (int i = 0; i < jsonStrings.length; i++) {
            PairOfUidAndBookId pairOfUidAndBookId = new PairOfUidAndBookId();
            String[] uidAndBookIds = jsonStrings[i].split(",");
            pairOfUidAndBookId.setUserId(Integer.parseInt(uidAndBookIds[0]));
            pairOfUidAndBookId.setBookId(Integer.parseInt(uidAndBookIds[1]));

            pairOfUidAndBookIds[i] = pairOfUidAndBookId;
        }

        return pairOfUidAndBookIds;
    }

    public void storeBorrowedBook(PairOfUidAndBookId[] pairOfUidAndBookIds, String filename)throws IOException{
        int booksUseLen = 0;
        for (int i = 0; i < pairOfUidAndBookIds.length; i++) {
            if(pairOfUidAndBookIds[i] != null){
                booksUseLen++;
            }
        }

        StringBuilder jsonArray = new StringBuilder();
        for (int i = 0; i < booksUseLen; i++) {
            jsonArray.append(pairOfUidAndBookIds[i].toJson());
            if(i != booksUseLen - 1){
                jsonArray.append("\n");
            }
        }

        FileUtils.writeFile(jsonArray.toString(), filename);
    }
}
